<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2017/2/27
 * Time: 12:27
 */

namespace Admin\Controller;


use Common\Controller\AdminController;

class GoodsListController extends AdminController
{
    public function lists(){
        $gid = I('get.gid');
        if(IS_POST){
            if(I('post.glid')){
                $this->editGoodsList(I('post.'));
            }else{
                $this->addGoodsList($gid);
            }
        }

        $oldData = M('GoodsList')->where("gid=$gid")->select();
        foreach($oldData as $k => $v){
            $oldData[$k]["groupid"] = explode('|',$v["groupid"]);
            foreach($oldData[$k]["groupid"] as $kk => $vv){
                $oldData[$k]["value"][] = M('GoodsAttr')->where("gaid=$vv")->getField("gattr");
            }
        }
//        dd($oldData);
        $this->assign("oldData",$oldData);

        // 获取商品规格数据
        $data = M("tproperty")->alias("tp")->join("xm_goods_attr ga on tp.tpid = ga.tpid")->where("gid={$gid} and tptype=2")->field("tp.tpid,tpname,gaid,gattr")->select();
        $arr = [];
        foreach($data as $k => $v){
            $arr[$v['tpname']]["name"] = $v['tpname'];
            $arr[$v['tpname']]["value"][] = $v;
        }
//        dd($arr);
        $this->assign("arr",$arr);
        $this->display();
    }

    public function addGoodsList($gid){
        $glData = I('post.');
        $glData['gid'] = $gid;
        $glData['groupid'] = '';
        foreach($glData['spec'] as $k => $v){
            $glData['groupid'] .= $v . '|';
        }
        $glData['groupid'] = rtrim($glData['groupid'],'|');
//        dd($glData);
        M('GoodsList')->add($glData);
    }

    public function editGoodsList($data){
        M('GoodsList')->save($data);
    }

    public function delGoodsList(){
        $glid = I("post.id");
        if($glid){
            $res = M('GoodsList')->where("glid=$glid")->delete();
            if($res){
                return show(1,'删除成功');
            }else{
                return show(0,'删除失败');
            }
        }
    }
}